import MyEditor from '@/components/MyEditor';
import MyUpload from '@/components/MyUpload';
import {
  addOneAPI,
  deleteByIdAPI,
  deleteManyByIds,
  loadDataAPI,
  loadOneByIdAPI,
  modifyByIdAPI,
} from '@/services/doctors';
import { loadAllHospitalsAPI } from '@/services/hospitals';
import { dalImg } from '@/utils/tools';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Popconfirm, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';

function WorkList() {
  const [isShow, setIsShow] = useState(false);
  const actionRef = useRef<ActionType>();
  const [currentID, setCurrentID] = useState(''); //记录当前id,用于区分是新增还是修改
  const [myForm] = ProForm.useForm(); //获取表单

  const [imageUrl, setImageUrl] = useState('');
  const [html, setHtml] = useState('');
  const [hospitals, setHospitals] = useState([]);

  useEffect(() => {
    loadAllHospitalsAPI().then((res) => {
      setHospitals(
        res.data.list.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        }),
      );
    });
  });

  // 选中的id
  const [selRows, setSelRows] = useState<any>([]);

  useEffect(() => {
    // 关闭之后重置数据
    if (!isShow) {
      setCurrentID('');
      setImageUrl('');
      setHtml('');
    }
  }, [isShow]);

  // 当前的数据列
  const columns: ProColumns[] = [
    {
      title: '序号',
      align: 'center',
      hideInSearch: true,
      width: 80,
      render(c, r, i) {
        return i + 1;
      },
    },
    {
      title: '名字 ',
      dataIndex: 'name',
    },
    {
      title: '医院',
      hideInSearch: true,
      render(c, v: Hospital.IDoctor) {
        return <>{v.hospitalInfo?.name}</>;
      },
    },
    {
      title: '科室',
      hideInSearch: true,
      render(c, v: Hospital.IDoctor) {
        return <>{v.hospitalInfo?.name}</>;
      },
    },
    {
      title: '职称',
      hideInSearch: true,
      render(c, v: Hospital.IDoctor) {
        return <>{v.doctorTitleInfo?.name}</>;
      },
    },
    {
      title: '标签',
      hideInSearch: true,
      dataIndex: 'tags',
    },
    {
      title: '简介',
      hideInSearch: true,
      // dataIndex 截取
      dataIndex: 'desc',
      ellipsis: true,
    },
    {
      title: '主图',
      hideInSearch: true,
      render(v: any) {
        return <img className="t-img" src={dalImg(v.avatar)} alt="" />;
      },
    },

    {
      title: '操作',
      hideInSearch: true,
      render(v: { id: string }) {
        return (
          <Space>
            <Button
              // 根据id修改
              icon={<EditOutlined />}
              type="primary"
              size="small"
              danger
              onClick={async () => {
                //获取数据
                const info = await loadOneByIdAPI(v.id);
                console.log(info);
                myForm.setFieldsValue(info.data);
                setIsShow(true);
                setCurrentID(v.id); //这样就可以根据id判断新增还是修改
                setImageUrl(info.data.image);
                setHtml(info.data.content);
              }}
            />
            {/* 根据id删除 */}
            <Popconfirm
              title="是否确认删除"
              onConfirm={async () => {
                await deleteByIdAPI(v.id);
                actionRef.current?.reload();
              }}
            >
              <Button icon={<DeleteOutlined />} type="primary" size="small" />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  // const data = [];
  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        // 这个属性可以直接操作表格中的各种方法
        rowSelection={{
          selectedRowKeys: selRows, //设置当前选中的
          onChange(selectedRowKeys) {
            // console.log(selectedRowKeys);
            setSelRows(selectedRowKeys);
          },
        }}
        // 这个属性可以直接操作数据中的各种操作
        actionRef={actionRef}
        columns={columns}
        // request是proTable中很重要的一个api,集成了表格中的内容
        request={loadDataAPI}
        // dataSource={data}
        toolBarRender={() => {
          // 操作按钮数据,魔人只有一个新增按钮
          const tools = [
            <Button
              type="primary"
              icon={<PlusOutlined />}
              key={1}
              onClick={() => {
                setIsShow(true);
              }}
            />,
          ];
          //如果勾选了指定的行,显示多行删除按钮
          if (selRows.length > 0) {
            tools.push(
              <Button
                type="primary"
                danger
                key={2}
                onClick={async () => {
                  // 通过join拼接数组
                  await deleteManyByIds(selRows.join(','));
                  actionRef.current?.reload(); //删除之后重新加载数据
                  setSelRows([]); //清空选择的值
                }}
              >
                批量删除
              </Button>,
            );
          }
          return tools;
        }}
      />

      {/* 模态表单 */}
      <ModalForm
        form={myForm}
        title="编辑"
        open={isShow}
        // 表示模态框的属性

        modalProps={{
          maskClosable: false, //点击遮罩层的时候不关闭
          destroyOnClose: true,
        }}
        // open状态不改变
        onOpenChange={setIsShow}
        onFinish={async (v) => {
          console.log(v);
          // 提交的时候执行
          if (currentID) {
            await modifyByIdAPI(currentID, { ...v, avatar: imageUrl, content: html }); //调接口取数据
          } else {
            await addOneAPI({ ...v, avatar: imageUrl, content: html }); //调接口存储数据
          }

          setIsShow(false);
          actionRef.current?.reload(); //重新加载数据
        }}
      >
        <ProFormText
          label="名字"
          placeholder="请输入名字"
          name="name"
          rules={[
            {
              required: true,
              message: '名字不能为空',
            },
          ]}
        />
        <ProForm.Item label="主图">
          <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl} />
        </ProForm.Item>
        <ProFormSelect label="医院" options={hospitals} name="hospitalId"></ProFormSelect>

        <ProFormTextArea label="简介" placeholder="请输入简介" name="desc"></ProFormTextArea>

        <ProForm.Item label="详情">
          <MyEditor html={html} setHtml={setHtml} />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
}

export default WorkList;
